package XishiBackend.services.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import XishiBackend.models.entity.Distribution;
import XishiBackend.models.entity.User;
import XishiBackend.models.repository.DistributionRepository;
import XishiBackend.models.repository.UserRepository;

@Service
@Transactional
public class WebUserService {
    @Autowired
    private UserRepository uR;
    @Autowired
    private DistributionRepository dR;
    
    public User findOne(long userId) {
        return uR.findOne(userId);
    }
    
    public List<User> findAll() {
        Iterator<User> iter = uR.findAll().iterator();
        List<User> list = new ArrayList<User>();
        while(iter.hasNext()) {
            User u = iter.next();
            list.add(u);
        }
        return list;
    }
    
    public List<User> findUserByTel(String tel) {
        return uR.findByTel(tel);
    }
    
    public Distribution findDistribution(long distributionId) {
        return dR.findOne(distributionId);
    }
    
    public boolean save(User u){
        User ru = uR.save(u);
        if(!ru.getTel().equals(u.getTel())) {
            return false;
        }
        if(ru.getDistributionId() != u.getDistributionId()) {
            return false;
        }
        if(ru.isBlack() != u.isBlack()) {
            return false;
        }
        if(Float.compare(ru.getMoney(), u.getMoney()) != 0) {
            return false;
        }
        return true;
    }
}
